﻿Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Partial Public Class upload1
    Inherits CoreClass

    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Try

            Dim postedFile As HttpPostedFile = Request.Files("Filedata")
            Dim id As String = Request.Params("GalleryID")
            Dim strDateFolder As String = Format(Now(), "yyyy\\MM\\dd\\")
            Dim strWebSrc As String = "EditorData\image\Gallery\" & strDateFolder & id & "\"
            Dim strSaveFolder As String = Server.MapPath("/") & strWebSrc
            'Kiểm tra sự tồn tại của thư mục
            If Not System.IO.Directory.Exists(strSaveFolder) Then
                'Tạo thư mục
                Call System.IO.Directory.CreateDirectory(strSaveFolder)
            End If

            Dim filename As String = GetUploadFileName(strSaveFolder, objFunction.ClearSpecialSymbol(objFunction.UnicodeToPlain(postedFile.FileName)))

            postedFile.SaveAs(strSaveFolder & filename)

            ' Thumbnail Image
            Dim arr As String() = Split(objConfig.Image5, "|", 2)
            Dim Img2W As Integer = 0
            Dim Img2H As Integer = 0
            Img2W = Integer.Parse(arr(0).ToString())
            Img2H = Integer.Parse(arr(1).ToString())
            Dim tempDimension As Integer = 0
            If Img2W > Img2H Then
                tempDimension = Img2W
            Else
                tempDimension = Img2H
            End If
            Dim objThumb As New Thumbnail.Thumbnail
            objThumb.InputFile = strSaveFolder & filename
            objThumb.Scale = True
            objThumb.Width = tempDimension
            objThumb.Height = tempDimension
            objThumb.CropWidth = Img2W
            objThumb.CropHeight = Img2H
            objThumb.CropType = Thumbnail.CropType.MiddleCenter
            Dim fileThumb As String = objThumb.CreateThumbnail()
            objThumb = Nothing
            ' END Thumbnail Image

            ' Update du lieu vao Db
            sql = "spi_GalleryUpdate "
            sql &= objFunction.ValueCheck(id) & ","
            sql &= objFunction.FieldCheck(strWebSrc & filename) & ","
            sql &= objFunction.FieldCheck(strWebSrc & fileThumb)
            objData.ExeNonQuery(sql)
            '0 = Xóa, 1 = Thêm mới, 2 = Update, 3 = Khác
            objFunction.writeLog(Session("UserId"), 1, "Upload ảnh Gallery cho sản phẩm có ID = " & id, "Tên ảnh: " & filename, "")
            ' write ra ten file de ben trang upload nhan duoc thong tin
            Response.Write(filename & ":" & fileThumb)
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try
    End Sub

    'Lấy tên file + đường dẫn để save file
    Public Function GetUploadFileName(ByVal strPath As String, ByVal strFilename As String, Optional ByVal AddDatePath As Boolean = False) As String
        'Khai báo biến Regular Expression
        Dim MatchResults As System.Text.RegularExpressions.Match

        Dim strAdditionFolder As String = IIf(AddDatePath, Format(Now(), "\\yyyy\\MM\\dd\\"), "")
        Dim strSaveFile As String = strFilename
        Dim strSaveFolder As String = strPath & strAdditionFolder

        Try
            'Kiểm tra sự tồn tại của thư mục
            If Not System.IO.Directory.Exists(strSaveFolder) Then
                'Tạo thư mục
                Call System.IO.Directory.CreateDirectory(strSaveFolder)
            End If
            'Kiểm tra nếu file đã tồn tại thì tạo tên khác
            While System.IO.File.Exists(strSaveFolder & strSaveFile)
                MatchResults = System.Text.RegularExpressions.Regex.Match(strSaveFile, "(?<FileName>.*?)(?:\((?<AutoNumber>\d*?)\))?\.(?<FileType>\w*?)(?!.)")
                If MatchResults.Success Then
                    If MatchResults.Groups("AutoNumber").Value = vbNullString Then
                        strSaveFile = MatchResults.Groups("FileName").Value & "(1)." & MatchResults.Groups("FileType").Value
                    Else
                        strSaveFile = MatchResults.Groups("FileName").Value & "(" & (Integer.Parse(MatchResults.Groups("AutoNumber").Value) + 1).ToString & ")." & MatchResults.Groups("FileType").Value
                    End If
                End If
            End While
        Catch ex As Exception
            If objConfig.Developer.Equals("1") Then
                objAlert.ErrorBox(Page, "File: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.DeclaringType.Name & _
                                  " --- Function: " & (New System.Diagnostics.StackTrace).GetFrame(0).GetMethod.Name & _
                                  " --- Mess: " & ex.Message.Replace("'", """"))
            Else
                objAlert.ErrorBox(Page, "Lỗi kỹ thuật, hãy thông báo lại với Admin, xin cảm ơn.")
            End If
        End Try
        'tmpUploadFile.VirtualPath = strAdditionFolder.Replace("\", "/") & strSaveFile
        'tmpUploadFile.Filename = strSaveFile
        'tmpUploadFile.FullPath = strSaveFolder & strSaveFile
        Return strSaveFile
    End Function

End Class